.bashrc git branch
It is often useful to display your current git branch in your prompt - but not obvious how to do it.
Embedding function calls in the prompt
Example basic prompt:
export PS1="${USER}@${HOST} \w\n"
Example prompt with embedded function call:
export PS1="${USER}@${HOST} \$(date -I) \w\n"
In the example with the embedded call, notice how it is backslash escaped.
Getting the current git branch
git_branch() {
git status --porcelain -b 2> /dev/null | grep -Po "(?<=^## )[^\.]+" 2>/dev/null
if [ "$?" -gt 0 ]; then
echo "--"
fi
}
git branch() {
# Save original directory
local dir="`pwd`"
# Move upwards through the directory tree until a .git directory is found
while [ "`pwd`" != "/" ] && ! [ -e ".git" ]; do cd ..; done
# If it has been found, echo the branch of HEAD, else echo "--"
if [ -e ".git" ]; then grep -Eo "[^/]+$" .git/HEAD; else echo "--"; fi
# Restore original directory
cd "$dir"
}